/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package app;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
/**
 *
 * @author CygiDawid
 */
public class SleepAlert {
    private java.util.Timer timerAsk;
    //private java.util.Timer timerAnswer;
    private Timer timerAnswer;
    private ActionListener answerTimesUp;
    private Asker asker;
   static private Name name;
    private QuestionDialog questionForm;
    private InfoDialog infoForm;
    private SettingsDialog settingsForm;
    private Settings settings = Settings.getSettings();
    static private String _actualTime = "";
    static boolean isReply = true;
    static boolean wrongReply = false;
    static boolean adminIsOnline = false;
    
    private class AskTimerTask extends TimerTask {
        @Override
        public void run() {
            if(adminIsOnline!=true){
            showQuestion();
            }
        }
    }
    
    
    public SleepAlert() {
        asker = new Asker(System.getProperty("user.dir") + "\\questions.txt");
        
        createTimers();
        
        settingsForm = new SettingsDialog(null, true);
        questionForm = new QuestionDialog(null, true);
        
        createTray();
        
    }
    
    private void createTimers() {
        answerTimesUp = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // powinno wyświelić wiadomość o braku odpowiedzi
                timerAnswer.stop();
                questionForm.dispose();
               
               // actualTime("Brak odpowiedzi!");
                 isReply = false;
                try {                
                    new Stats();
                } catch (IOException ex) {
                    Logger.getLogger(SleepAlert.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                isReply = true;
                
                
            }
        };
        
        timerAnswer = new Timer(settings.getAnswerTime(), answerTimesUp);
    }
    
    private void createTray() {
        if (!SystemTray.isSupported()) {
            System.out.println("Nie można dodać ikony do zasobnika systemowego.");
            return;
        }
        
        PopupMenu popup = new PopupMenu();
        TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage("trayIcon.png"));
        SystemTray tray = SystemTray.getSystemTray();
        
        MenuItem aboutItem = new MenuItem("O programie");
        aboutItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showAbout();
            }
        });/*
        MenuItem logItem = new MenuItem("Przeloguj");
        logItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                relogin();
            }
        });*/
        MenuItem statsItem = new MenuItem("Statystyki");
        statsItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showStatistics();
            }
        });
        MenuItem settsItem = new MenuItem("Ustawienia");
        settsItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showSettings();
            }
        });
        MenuItem exitItem = new MenuItem("Zakończ");
        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) { 
                closeApp();
            }
        });
       
        popup.add(aboutItem);
        //popup.addSeparator();
        //popup.add(logItem);
        
        if (Name.name.trim().toLowerCase().equals(Name.adminLogin) && Name.pass.toLowerCase().equals(Name.adminPassword))
        {
            adminIsOnline = true;
            popup.addSeparator();
            popup.add(statsItem);
            popup.add(settsItem);
        }
        popup.addSeparator();
        popup.add(exitItem);
       
        trayIcon.setPopupMenu(popup);
       
        try {
            tray.add(trayIcon);
        }
        catch (AWTException e) {
            System.err.println("Nie udało się dodać ikonę do zasobnika systemowego.");
        }
    }
    
    
    private void showQuestion() {
        stop();
        System.out.println("jest");
        String[] info = asker.getNextQuestion();
        questionForm.setQuestion(info[0], info[1]);

        timerAnswer.start();
        questionForm.setVisible(true);
        timerAnswer.stop();
        start();
        
        if (questionForm.getAnswerState() == AnswerState.Wrong) {
           // actualTime("Błędna odpowiedź!!");
            wrongReply = true;
          
                try {
                    new Stats();
                } catch (IOException ex) {
                    Logger.getLogger(SleepAlert.class.getName()).log(Level.SEVERE, null, ex);
                
           
            }
            wrongReply = false;
        }
    }
    
    private void showSettings() {
        // ukazanie okienka do podania hasła i jeżeli hasło jest poprawne ukazanie ustawień
        stop();
        settingsForm.setVisible(true);
        if (settingsForm.isSaved()) {
            timerAnswer = new Timer(settings.getAnswerTime(), answerTimesUp);
        }
        start();
    }
    
    private void relogin() {
        
    }
    
    private ReadingStatistics statsForm = new ReadingStatistics();
    private void showStatistics() {
        stop();
        statsForm.setVisible(true);
        start();
    }
    
    private void showAbout() {
        if (infoForm == null) {
            infoForm = new InfoDialog();
        }
        
        infoForm.setVisible(true);
    }
    
    public void closeApp() {
        Settings.getSettings().Save();
        System.exit(0);
    }
    
    
    public void start() {
        /*
        AdminLogin login = new AdminLogin();
        login.setVisible(true);
        */
        timerAsk = new java.util.Timer(true);
        timerAsk.schedule(new AskTimerTask(), Settings.getSettings().getAskTime(), Settings.getSettings().getAskTime());
    }
    
    public void stop() {
        if (timerAsk != null) {
            timerAsk.cancel();
        }
    }
    
    public void answerd() {
        if (timerAnswer != null && timerAnswer.isRunning()) {
            timerAnswer.stop();
        }
    }
    /*
    public static void actualTime(String message){
                SimpleDateFormat simpleDateThere = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss ");
                simpleDateThere.setTimeZone( TimeZone.getTimeZone("Poland") );
                _actualTime = simpleDateThere.format(new Date());
                System.out.println(_actualTime+": "+ message);
       
    }*/
    
    public static void main(String[] args) {
        name = new Name();
        name.setVisible(true);
        
    }
}
